// pages/mess/mess.js
// import logger from '../../utils/logger';

const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        isTimLogin: false,
        conversationList: [],
        showSelectTag: false,
        index: Number,
        unreadCount: 0,
        conversationInfomation: {},
        transChenckID: '',
        csTimeText: '97-01-01',
        _titIndex: 1,
        // 回收订单
        recycleOrderText: '',
        recycleOrderDate: '',
        recycleOrderNotRead: false,
        // 商品订单
        shopOrderText: '',
        shopOrderDate: '',
        shopOrderNotRead: false
    },
    /**
     * 获取订单信息列表
     */
    getMessList() {
        this.getShopMess();
        this.getRecycleMess();
    },
    /**
     * 获取商品订单消息
     */
    getShopMess() {
        wx.cloud.callFunction({
            name: 'databaseApi',
            data: {
                type: 'getMessList',
                reqData: {
                    timeStamp: new Date().getTime(),
                    type: 'shop'
                }
            }
        }).then(res => {
            // console.log('getGoodsMessList success ==>', res);
            let messList = res.result.resData;
            this.setData({
                shopOrderNotRead: !messList[0].isRead
            });
            let shopStateText = ['待支付', '待发货', '已发货', '售后中', '已完成', '待退款', '已退款'];
            this.setData({
                shopOrderText: '您的订单' + shopStateText[messList[0].orderState],
                shopOrderDate: this.timeFormat(messList[0].createTime)
            });
        }, err => {
            console.log('getGoodsMessList error ==>', err);
        });
    },
    /**
     * 获取回收订单消息
     */
    getRecycleMess() {
        wx.cloud.callFunction({
            name: 'databaseApi',
            data: {
                type: 'getMessList',
                reqData: {
                    timeStamp: new Date().getTime(),
                    type: 'recycle'
                }
            }
        }).then(res => {
            // console.log('getRecycleMessList success ==>', res);
            let messList = res.result.resData;
            this.setData({
                recycleOrderNotRead: !messList[0].isRead
            });
            if(messList[0].orderState === 0) {
                this.setData({
                    recycleOrderText: '您的订单即将上门回收',
                    recycleOrderDate: this.timeFormat(messList[0].createTime)
                });
            }else if(messList[0].orderState === 1) {
                this.setData({
                    recycleOrderText: '您的订单已上门回收',
                    recycleOrderDate: this.timeFormat(messList[0].createTime)
                });
            }else if(messList[0].orderState === 2) {
                this.setData({
                    recycleOrderText: '您的订单已完成',
                    recycleOrderDate: this.timeFormat(messList[0].createTime)
                });
            }
        }, err => {
            console.log('getRecycleMessList error ==>', err);
        });
    },
    /**
     * 跳转到商品通知
     */
    onToGoodsNotice() {
        wx.navigateTo({
          url: '/pages/order_notice/order_notice?type=商品订单&checked=' + !this.data.shopOrderNotRead,
        });
    },
    /**
     * 跳转到回收通知
     */
    onToRecycleNotice() {
        wx.navigateTo({
          url: '/pages/order_notice/order_notice?type=回收订单&checked=' + !this.data.recycleOrderNotRead,
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },
    /**
     * 点击上方的标题并显示相应内容
     */
    onClickTitle(e) {
        // index: 1-私信，2-系统通知
        let index = e.currentTarget.dataset.index;
        this.setData({
            _titIndex: index
        });
    },
    // 跳转到子组件需要的参数
    handleRoute(event) {
        const flagIndex = this.data.conversationList.findIndex(item => item.conversationID === event.currentTarget.id);
        this.setData({
            index: flagIndex,
        });
        this.getConversationList();
        this.data.conversationInfomation = {
            conversationID: event.currentTarget.id,
            unreadCount: this.data.conversationList[this.data.index].unreadCount
        };
        const url = `/pages/chat/chat?conversationInfomation=${JSON.stringify(this.data.conversationInfomation)}`;
        wx.navigateTo({
            url,
        });
    },
    // 更新会话列表
    onConversationListUpdated(event) {
        // logger.log('| TUI-conversation | onConversationListUpdated | ok');
        this.setData({
            conversationList: event.data,
        });
    },
    // 获取会话列表
    getConversationList() {
        wx.$TUIKit.getConversationList().then((imResponse) => {
            // logger.log(`| TUI-conversation | getConversationList | getConversationList-length: ${imResponse.data.conversationList.length}`);
            this.setData({
                conversationList: imResponse.data.conversationList,
            });
        });
    },
    /**
     * 格式化时间
     * 将 yy/MM/DD 转化为 yy-MM-DD
     * @param {String} dateStr
     */
    timeFormat(dateStr) {
        return dateStr.replace(/\//g, '-');
    },
    /**
     * 获取当前日期
     *  - 格式：yy-MM-DD
     */
    getNowDate() {
        let date = new Date();
        let dateText = (date.getFullYear() % 100) + '-' + (('0' + (date.getMonth() +1)).slice(-2)) + '-' + (('0' + date.getDate()).slice(-2));
        this.setData({
            csTimeText: dateText
        });
    },
    /**
     * 客服按钮的处理事件
     * @param {*} e 
     */
    handleContact(e) {},
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getNowDate();
        this.setData({
            isTimLogin: app.globalData.isTimLogin
        });
        if(app.globalData.isTimLogin) {
            wx.$TUIKit.on(wx.$TUIKitEvent.CONVERSATION_LIST_UPDATED, this.onConversationListUpdated, this);
            this.getConversationList();
        }
        this.getMessList();
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        wx.$TUIKit.off(wx.$TUIKitEvent.CONVERSATION_LIST_UPDATED, this.onConversationListUpdated);
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})